<template>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="formInline.username"></el-input>
        </el-form-item>
         <el-form-item label="电子邮箱">
          <el-input v-model="formInline.email"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formInline.type" placeholder="请选择类型">
             <el-option
              v-for="item in typeOption"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formInline.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOption"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="VIP起始时间">
            <el-date-picker
              v-model="date"
              type="datetimerange"
              start-placeholder="开始日期"
              @change="changeDate"
              end-placeholder="结束日期" >
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="24" style="text-align: left">
      <el-button><router-link :to="{path:'/manage/userinfo'}"> 添加用户</router-link></el-button>
      <el-button @click="openDailog('score')">批量添加积分</el-button>
      <el-button @click="openDailog('time')">批量添加VIP到期时间</el-button>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>

        <el-table-column label="状态">
          <template slot-scope="scope">{{ scope.row.status|status }}</template>
        </el-table-column>

        <el-table-column label="类型">
          <template slot-scope="scope">{{ scope.row.type|type }}</template>
        </el-table-column>
        <el-table-column prop="score" label="积分" show-overflow-tooltip>
        </el-table-column>
         <el-table-column prop="mail" label="电子邮箱" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="mobile" label="手机" show-overflow-tooltip>
        </el-table-column>

        <el-table-column label="vip到期时间" >
          <template slot-scope="scope">{{ scope.row.vipEndTime|dateFormat }}</template>
        </el-table-column>
       <el-table-column label="最后登录时间" >
          <template slot-scope="scope">{{ scope.row.loginTime|dateFormat}}</template>
        </el-table-column>
        <el-table-column label="创建时间" >
          <template slot-scope="scope">{{ scope.row.createTime|dateFormat}}</template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button  type="text" size="small"
              ><router-link :to="{name:'userinfo',query:{id:scope.row.id}}"> 编辑</router-link></el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination"> </div>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.currentPage"
      :page-sizes="[10,20,30,40,50]"
      :page-size="pageInfo.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>

      <el-dialog title="批量修改" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="addForm">
          <el-form-item v-if="batchTtype=='score'" label="请输入积分" label-width="100px">
            <el-input v-model="form.score" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-else label="请输入秒数" label-width="100px">
             <el-input placeholder="请输入秒数" v-model="form.date" autocomplete="off">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="addInfo()">确 定</el-button>
        </div>
      </el-dialog>
    </el-col>
  </el-row>
</template>
<script>
import store from '@/store'
import { batchScore,batchTime} from '@/api/service'
import {fieldMap ,publicFilter} from '@/utils/showMap'
export default {
  data() {
    return {
      batchTtype:'score',
      dialogFormVisible:false,
      form: {//批量新增表单
          score: '',
          date:'',
        },
      statusOption:fieldMap.user_status,
      typeOption:fieldMap.user_type,
      date:'',
      formInline: { //查询条件表单
        state: "",
        username: "",
        email: "",
        type: "",
        status: "",
        vipBeginTime: "",
        vipEndTime: "",
      },
      pageInfo:{
          currentPage: 1,
          size:15,
          total:0,
      },
      tableData: [],
      multipleSelection: [],
    };
  },
   filters: {
    status: value=>publicFilter(fieldMap.user_status,value),
    type: value=>publicFilter(fieldMap.user_type,value),
    dateFormat:(args)=>{
          let fmt="YYYY-mm-dd HH:MM:SS"
          let ret;
          if(args){
            let  date=new Date(args)
               const opt = {
              "Y+": date.getFullYear().toString(),        // 年
              "m+": (date.getMonth() + 1).toString(),     // 月
              "d+": date.getDate().toString(),            // 日
              "H+": date.getHours().toString(),           // 时
              "M+": date.getMinutes().toString(),         // 分
              "S+": date.getSeconds().toString()          // 秒
          };
          for (let k in opt) {
              ret = new RegExp("(" + k + ")").exec(fmt);
              if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
              };
          };
          return fmt;
          }else{
            return "";
          }

      },
  },
  mounted(){
    this.search();
  },
  methods: {
    openDailog(args){
      //设置积分
      if(this.multipleSelection.length){
         this.batchTtype=args;
         this.dialogFormVisible=true;
      }else{
         this.$message.error('请先勾选用户');
      }
    },
    addInfo(){
        let data={
          ids:this.multipleSelection.map(item=>item.id),
          value:this.batchTtype=='score'?this.form.score:this.form.date,
        }
        if(this.batchTtype=='score')
        batchScore(data).then(res=>{
          if(res.status==200){
             this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.search();
          }else{
            this.$message.error(res.msg||'接口错误');
          }
           this.$refs.addForm.resetFields();
           this.dialogFormVisible=false;
        })
        else
        batchTime(data).then(res=>{
          if(res.status==200){
             this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.search();
          }else{
            this.$message.error(res.msg||'接口错误');
          }
          this.$refs.addForm.resetFields();
           this.dialogFormVisible=false;
        })
    },
    cancel(){
      this.dialogFormVisible=false;
      this.$refs.addForm.resetFields();
    },
    changeDate(){
      let a=this.date[0];
      let b=this.date[1];
       this.formInline.vipBeginTime=this.dateFormat(a,"YYYY-mm-dd HH:MM:SS");
       this.formInline.vipEndTime=this.dateFormat(b,"YYYY-mm-dd HH:MM:SS");
    },
    search(){
         store.dispatch('user/getUserList',{page:this.pageInfo.currentPage,size:this.pageInfo.size,...this.formInline}).then(res=>{
          this.tableData=res.data.content;
          this.pageInfo.currentPage=res.data.page;
          this.pageInfo.total=res.data.total;
          this.pageInfo.size=res.data.size;
     })
    },
    onSubmit() {
      console.log("submit!");
      this.search();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleClick(row) {
      // console.log(row);
    },
    addUser() {
      //添加用户
      this.$router.push({path:'/manage/userinfo'})

    },
    dateFormat: (args, fmt) => {
        //let fmt="YYYY-mm-dd"
        let ret;
        if (args) {
          let date = new Date(args)
          const opt = {
            "Y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString() // 秒
          };
          for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
              fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
          };
          return fmt;
        } else {
          return "";
        }
      },
      handleSizeChange(val) {
       this.pageInfo.size=val;
      this.search();
      },
      handleCurrentChange(val) {
         this.pageInfo.currentPage=val;
        this.search();
      }
  },
};
</script>
<style lang="less" scoped>
.demo-form-inline {
  text-align: left;
}
.pagination{
  margin:15px auto;
}
</style>
